﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.IO.Ports;
using System.IO;
using System.Net;

namespace comm_num_tp1
{
    public partial class frmMain : Form
    {
        bool bStop;
        private string m_statbarsplitter;
        private DateTime m_dtstart;
        private int m_nbkm;
        private string m_status;

        private string m_CamionID;
        private bool hasRecievedNewChat;

        private bool m_HasSentMap;


        /**********PARTIE ANTENNE******
         * 
         * 
         * 
         * 
         * */
        private GpsAcquireStream _gpsToDevice = new GpsAcquireStream();

        delegate void AddAllGpsStream(object sender, GpsStreamEventArgs gpsE);

        bool m_IsFixAcquired;
        string m_Lat;
        string m_Lon;


        /// <summary>
        /// Constructeur de la form
        /// </summary>
        public frmMain()
        {
            //STOCK COSMÉTIQUE
            bStop = true;
            InitializeComponent();
            m_status = "INACTIF";
            m_statbarsplitter = " |                          | ";
            m_CamionID = "0";
            //FIN STOCK COSMÉTIQUE
            m_IsFixAcquired = false;
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            
            //Le fichier est "hardcodé" dans le client pour l'instant
            //if (!Directory.Exists("C:\\gpsserver"))
                //Directory.CreateDirectory("C:\\gpsserver");

            //StreamWriter sw = new StreamWriter("C:\\gpsserver\\index.html");
            //sw.Write(Properties.Resources.index);
            //sw.Flush();
            //sw.Close();
            
            //googleMap.Navigate("C:\\gpsserver\\index.html");
            

            RefreshStatBar();
            SetInitialWindowComponent();
        }


        /// <summary>
        /// Rafraichit la barre de statut
        /// </summary>
        private void RefreshStatBar()
        {
            //Probable calculs à implémenter sur le client

            //string temps = (DateTime.Now - m_dtstart).Hours.ToString() + ":" + (DateTime.Now-m_dtstart).Minutes.ToString() + ":" + (DateTime.Now-m_dtstart).Seconds.ToString();
            //string vitesse = ((DateTime.Now-m_dtstart).Hours / m_nbkm).ToString() + "KM/H";

            //Pour débug affichage
            string temps = "00:00:00";
            string vitesse = "000KM/H";

            lblStatBarMessage.Text = "Camion " + m_CamionID + m_statbarsplitter + "Temps écoulé : " + temps + m_statbarsplitter + "Vitesse moyenne : " + vitesse + m_statbarsplitter + "Status du camion : " + m_status;
        }




        //Trucs pour rendre le GPS fonctionnel
        private void démarrerToolStripMenuItem_Click(object sender, EventArgs e)
        {
            _gpsToDevice.GpGgaEvent += new GpsAcquireStream.GpsEventHandler(this.GpsStreamGga);
            _gpsToDevice.baudRate = 4800;
            _gpsToDevice.dataBits = 8;
            _gpsToDevice.parity = System.IO.Ports.Parity.None;
            Thread GpsThreadStartReading = new Thread(_gpsToDevice.GpsStreamStart);



            if (cboCom.SelectedIndex != -1)
            {
                _gpsToDevice.comName = cboCom.SelectedItem.ToString();
                if (_gpsToDevice.GpsConnect())
                {
                    GpsThreadStartReading.Start();
                }
            }

            try
            {
                thComm.Interval = Convert.ToInt32(txtInter.Text);
                thComm.Start();
                FetchClientWebPage();
                UpdateTruckStatusOnce("enable");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

        private void FetchClientWebPage()
        {
            UriBuilder url2;
            url2 = new UriBuilder("http", txtIpAdd.Text, Convert.ToInt32(txtIpPort.Text), "GpsTheMads/Client.aspx", "?asktrucklonlat=" + txtTruckID.Text);
            //url2 = new UriBuilder("http", txtIpAdd.Text, Convert.ToInt32(txtIpPort.Text), " gps-server/Client.aspx", "?asktrucklonlat=" + txtTruckID.Text);
            googleMap.Navigate(url2.Uri);
        }

        private void UpdateTruckStatusOnce(string truckstatus)
        {
            UriBuilder url2;
            //url2 = new UriBuilder("http", txtIpAdd.Text, Convert.ToInt32(txtIpPort.Text), " gps-server/Client.aspx", "?updatetruckstatus=" + truckstatus + "&truckno=" + txtTruckID.Text);
            url2 = new UriBuilder("http", txtIpAdd.Text, Convert.ToInt32(txtIpPort.Text), "GpsTheMads/Client.aspx", "?updatetruckstatus=" + truckstatus + "&truckno=" + txtTruckID.Text);
            webRequest.Url = url2.Uri;
        }

        private void GpsStreamGga(object sender, GpsStreamEventArgs gpsE)
        {
            if (txtGgaAllStream.InvokeRequired)
            {
                AddAllGpsStream AddAllGpsDelegate = new AddAllGpsStream(GpsStreamGga);
                txtGgaAllStream.Invoke(AddAllGpsDelegate, new object[] { sender, gpsE });
            }
            else
            {
                GpGGA tempStream = (GpGGA)gpsE.GetStream;
                txtGgaAllStream.Text = tempStream.ToString();

                if (((GpGGA)gpsE.GetStream).StreamFix == "1")
                {
                    txtDebugStream.Text = tempStream.ToString();
                    //Le fix est acquis
                    m_IsFixAcquired = true;
                    //Stocke la Lat
                    //Stock la lon
                    m_Lat = ((GpGGA)gpsE.GetStream).StreamLat;
                    m_Lon = ((GpGGA)gpsE.GetStream).StreamLon;
                }
            }
        }


        private void SetInitialWindowComponent()
        {
            string[] currentPort = SerialPort.GetPortNames();
            if (currentPort != null)
            {
                cboCom.Items.Clear();
                for (int i = 0; i < currentPort.Length; i++)
                    cboCom.Items.Add(currentPort[i]);
            }

        }

        private void voirTramesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MainWindow mw = new MainWindow();
            mw.Show();
        }

        private void quitterToolStripMenuItem_Click(object sender, EventArgs e)
        {
            _gpsToDevice.GpsStreamStop();
            _gpsToDevice.GpsDisconnect();
            _gpsToDevice = new GpsAcquireStream();
            //lbItineraire.Items.Clear();
            googleMap.Navigate("");
            m_IsFixAcquired = false;
            thComm.Stop();
            UpdateTruckStatusOnce("disable");
        }

        private void thComm_Tick(object sender, EventArgs e)
        {
            if (m_IsFixAcquired)
            {
                //Envoie 
                IPAddress ipAdd;
                ipAdd = IPAddress.Parse(txtIpAdd.Text);
                if (ipAdd != null)
                {
                    //Conversion Degré Minutes Secondes en Degré Décimal

                    int latDeg = Convert.ToInt32(m_Lat[0].ToString() + m_Lat[1]);
                    int lonDeg = Convert.ToInt32(m_Lon[0].ToString() + m_Lon[1] + m_Lon[2]);
                    string[] sLat = m_Lat.Split('.');
                    string[] sLon = m_Lon.Split('.');

                    string latOri = sLat[1][sLat[1].Length - 1].ToString();
                    string lonOri = sLon[1][sLon[1].Length - 1].ToString();

                    sLat[0] = sLat[0].Remove(0, 2);
                    sLon[0] = sLon[0].Remove(0, 3);
                    sLat[1] = sLat[1].Remove(sLat[1].Length - 2, 2);
                    sLon[1] = sLon[1].Remove(sLon[1].Length - 2, 2);

                    string sLatMin = sLat[0] + "," + sLat[1];
                    string sLonMin = sLon[0] + "," + sLon[1];

                    double LatMin = Convert.ToDouble(sLatMin) / 60.0;
                    double LonMin = Convert.ToDouble(sLonMin) / 60.0;

                    string sLatUTM = Convert.ToString((double)latDeg + LatMin).Replace(',', '.');

                    if (latOri.ToUpper() == "S")
                        sLatUTM = sLatUTM.Insert(0, "-");

                    string sLonUTM = Convert.ToString((double)lonDeg + LonMin).Replace(',', '.');

                    if (lonOri.ToUpper() == "W")
                        sLonUTM = sLonUTM.Insert(0, "-");

                   UriBuilder url = new UriBuilder("http", txtIpAdd.Text, Convert.ToInt32(txtIpPort.Text), "GpsTheMads/Coordinates.aspx", 
                        "?updatetrucklocation=true&" + "truckid=" + txtTruckID.Text + "&"+ "latitude=" + sLatUTM + "&" + "longitude=" + sLonUTM) ;
                   /* UriBuilder url = new UriBuilder("http", txtIpAdd.Text, Convert.ToInt32(txtIpPort.Text), " gps-server/Coordinates.aspx",
                        "?updatetrucklocation=true&" + "truckid=" + txtTruckID.Text + "&" + "latitude=" + sLatUTM + "&" + "longitude=" + sLonUTM);*/
                    webRequest.Url = url.Uri;
                   // webRequest.Refresh();

                    //Pour le chat

                    //UriBuilder url3;
                    //url3 = new UriBuilder("http", txtIpAdd.Text, Convert.ToInt32(txtIpPort.Text), " gps-server/Client.aspx", "?DateChat=" + DateTime.Now.ToString());
                    //webRequest.Url = url3.Uri;
                    //webRequest.Refresh();
                    ////MessageBox.Show(webRequest.Url.AbsolutePath);


                }
            }
        }

        private void menuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {

        }
    }
}
